import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../provider/library_provider.dart';
import '../../provider/user_provider.dart';
import '../widgets/library_game_card.dart';


class LibraryPage extends StatefulWidget {
  const LibraryPage({super.key});

  @override
  State<LibraryPage> createState() => _LibraryPageState();
}

class _LibraryPageState extends State<LibraryPage> {
  @override
  void initState() {
    super.initState();
    //确保在UI构建完成后再调用Provider，避免错误
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final user = context.read<UserProvider>().currentUser;
      if (user != null) {
        //调用LibraryProvider来获取数据
        context.read<LibraryProvider>().fetchLibrary(user.id);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final provider = context.watch<LibraryProvider>();
    final games = provider.libraryGames;

    return Scaffold(
      appBar: AppBar(
        title: const Text('库'),
      ),

      body: provider.isLoading
          ? const Center(child: CircularProgressIndicator())
          : provider.errorMessage != null
          ? Center(child: Text(provider.errorMessage!))
          : games.isEmpty
          ? const Center(child: Text('你的库中还没有游戏'))
          : GridView.builder(
        padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 16.0),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3, //每行三个卡片
          crossAxisSpacing: 12.0, //卡片之间的横向间距
          mainAxisSpacing: 12.0,  //卡片之间的纵向间距
          childAspectRatio: 0.66, //卡片宽高比
        ),
        itemCount: games.length,
        itemBuilder: (context, index) {
          final game = games[index];
          return LibraryGameCard(game: game);
        },
      ),
    );
  }

}